package com.luck.easyfoodbatch.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.AddressAdapter;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.DefaultAddressModel;
import com.luck.easyfoodbatch.mvp.mine.DefaultAddressPresenter;
import com.luck.easyfoodbatch.mvp.mine.DefaultAddressView;
import com.luck.easyfoodbatch.mvp.mine.DelAddressModel;
import com.luck.easyfoodbatch.mvp.mine.DelAddressPresenter;
import com.luck.easyfoodbatch.mvp.mine.DelAddressView;
import com.luck.easyfoodbatch.mvp.mine.MyAddressModel;
import com.luck.easyfoodbatch.mvp.mine.MyAddressPresenter;
import com.luck.easyfoodbatch.mvp.mine.MyAddressView;
import com.luck.easyfoodbatch.mvp.model.Address;
import com.luck.easyfoodbatch.mvp.model.DelAddress;
import com.luck.easyfoodbatch.mvp.model.MyAddress;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.luck.easyrecyclerview.sideslip.Closeable;
import com.luck.easyrecyclerview.sideslip.OnSwipeMenuItemClickListener;
import com.luck.easyrecyclerview.sideslip.SwipeMenu;
import com.luck.easyrecyclerview.sideslip.SwipeMenuCreator;
import com.luck.easyrecyclerview.sideslip.SwipeMenuItem;
import com.luck.easyrecyclerview.sideslip.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddressManagementActivity extends BaseActivity implements MyAddressView, DefaultAddressView, DelAddressView {

//    @BindView(R.id.right_title)
//    TextView rightTitle;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.iv_nodata)
    ImageView iv_nodata;
   private TextView tv_add_new_address;
    private AddressAdapter adapter;
    private DelAddressModel delAddressModel;
    private List<MyAddress.DataBean> list = new ArrayList<>();
    private int type = 0;
    private MyAddressModel addressModel;
    private int position = 0;// 点击设为默认地址时的下标
    private int address_type = 0;
    private String p_id = "3";
    private DefaultAddressModel defaultAddressModel;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.refresh")) {
                if (addressModel == null) {
                    addressModel = new MyAddressPresenter(AddressManagementActivity.this, mContext);
                }
                addressModel.getMyAddressList(address_type + "");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_address_management, "地址管理","新增", MODE_BACK_NAVIGATION);
        setContentView(R.layout.activity_address_management, "地址管理", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        tv_add_new_address= (TextView) findViewById(R.id.tv_add_new_address);
        p_id = (String) SharedPreferencesUtil.getData(AddressManagementActivity.this, HttpUtil.P_ID, "3");
        registerReceiver(receiver, "action.app.refresh");
        type = getIntent().getIntExtra("type", 0);// 1是修改地址 2是选择地址
        address_type = getIntent().getIntExtra("address_type", 0);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 7), getResources().getColor(R.color.color_f7)));
        recyclerView.setLayoutManager(manager);
        adapter = new AddressAdapter(mContext, list, onDefault,onDelecteAddress, type);
        adapter.setOnItemClickListener(new AddressAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                MyAddress.DataBean bean = list.get(position);

                if (type == 2) {
                    // 选择地址
                    if (bean.isChecked()) {
                        Intent intent = new Intent();
                        intent.putExtra("bean", bean);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 1);
                    bundle.putInt("address_type", address_type);
                    bundle.putSerializable("bean", bean);
                    startAct(NewlyAddedActivity.class, bundle);
                }
            }
        });

        showProgressDialog("正在加载，请稍候……");
        addressModel = new MyAddressPresenter(this, mContext);
        addressModel.getMyAddressList(address_type + "");
        adapter.setAddress_type(address_type);
        recyclerView.setAdapter(adapter);
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        recyclerView.setSwipeMenuItemClickListener(new OnSwipeMenuItemClickListener() {
            @Override
            public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, @SwipeMenuRecyclerView.DirectionMode int direction) {
                showProgressDialog("正在删除，请稍候……");
                closeable.smoothCloseMenu();// 关闭被点击的菜单。
                delAddressModel = new DelAddressPresenter(AddressManagementActivity.this, mContext);
                MyAddress.DataBean bean = list.get(adapterPosition);
                position = adapterPosition;
                delAddressModel.delAddress(bean.getAddress_id(), address_type + "");
            }
        });
        tv_add_new_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("address_type", address_type);
                startAct(NewlyAddedActivity.class, bundle);
            }
        });
    }


    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_height);

            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
                        .setBackgroundDrawable(R.drawable.selector_swipe_red)
                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
            }
        }
    };


    /**
     * 设置为默认地址
     */
    private AddressAdapter.OnDefault onDefault = new AddressAdapter.OnDefault() {
        @Override
        public void onDefault(String address_id, int index) {
            showProgressDialog("正在设置，请稍候……");
            position = index;
            defaultAddressModel = new DefaultAddressPresenter(AddressManagementActivity.this, mContext);
            defaultAddressModel.setDefaultAddress(address_id, address_type + "");
        }
    };

    /*
    删除地址
     */
    private AddressAdapter.OnDelecteAddressListener onDelecteAddress=new AddressAdapter.OnDelecteAddressListener() {
        @Override
        public void onDelectAddress(String address_id, int position) {
            showProgressDialog("正在删除，请稍候……");
            delAddressModel = new DelAddressPresenter(AddressManagementActivity.this, mContext);
            MyAddress.DataBean bean = list.get(position);
            delAddressModel.delAddress(bean.getAddress_id(), address_type + "");
        }
    };
    @OnClick(R.id.right_title)
    public void onClick() {
        Bundle bundle = new Bundle();
        bundle.putInt("address_type", address_type);
        startAct(NewlyAddedActivity.class, bundle);
    }

    @Override
    public void myAddressSuccess(MyAddress model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                list = model.getData();
                if (list == null) {
                    list = new ArrayList<>();
                }
                if (list.size() == 0) {
                    iv_nodata.setVisibility(View.VISIBLE);
                    sendBroadcast("action.app.refresh.address");
                } else {
                    iv_nodata.setVisibility(View.INVISIBLE);
                }
                for (MyAddress.DataBean item : list) {
                    if (type == 2) {
                        if (item.getProvince().equals(p_id)) {
                            item.setChecked(true);
                        } else {
                            item.setChecked(false);
                        }
                    }
                    if (item.getIs_default() == 1) {
                        User.DefaultAddressBean default_address = user.getDefault_address();
                        if (default_address == null) {
                            default_address = new User.DefaultAddressBean();
                        }
                        default_address.setAddress_id(item.getAddress_id());
                        default_address.setType(item.getType());
                        default_address.setAddress_str(item.getAddress_str());
                        default_address.setCity(item.getCity());
                        default_address.setIs_default(item.getIs_default() + "");
                        default_address.setMobile(item.getMobile());
                        default_address.setProvince(item.getProvince());
                        default_address.setStreet(item.getStreet());
                        default_address.setTown(item.getTown());
                        default_address.setUname(item.getUname());
                        default_address.setUid(item.getUid());
                        default_address.setCreated_at(item.getCreated_at());
                        default_address.setUpdated_at(item.getUpdated_at());
                        App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                    }
                }
                adapter.setList(list);
                adapter.notifyDataSetChanged();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void defaultSuccess(Address model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                addressModel.getMyAddressList(address_type + "");
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                Address.DataBean data = model.getData();
                bundle.putSerializable("bean", data);
                intent.putExtras(bundle);
                intent.setAction("action.app.refresh.default");
                sendBroadcast(intent);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void delAddressSuccess(DelAddress model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                list.remove(position);
                if (list.size() == 0) {
                    iv_nodata.setVisibility(View.VISIBLE);
                    sendBroadcast("action.app.refresh.address");
                } else {
                    iv_nodata.setVisibility(View.INVISIBLE);
                }
                adapter.notifyDataSetChanged();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
